<template>
  <div style="padding: 0 30px;">
    <div class="box">
      <div class="divider" />
      <el-row>
        <el-col :span="12">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            :rules="rules"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="品牌名称" prop="name">
              <el-input v-model="ruleForm.name" />
              <p class="beizhu">
                备注：英文标识，只允许含有：英文、数字、中划线
              </p>
            </el-form-item>
            <el-form-item label="品牌首字母" prop="pinyin">
              <el-input v-model="ruleForm.pinyin" />
            </el-form-item>
            <el-form-item label="品牌logo" prop="logo">
              <span
                class="beizhu"
              >备注：单图图片尺寸为：300*100，只能上传jpg/png文件，且大小不超过5MB</span>
              <!-- 隐藏域，提交上传的图片路径 -->
              <input v-model="ruleForm.logo" type="hidden">
              <el-upload
                class="avatar-uploader"
                name="logo"
                :data="{ brandNamePinyin: ruleForm.pinyin }"
                :action="UPLOAD_URL"
                :show-file-list="false"
                :on-success="handleLogoSuccess"
                :before-upload="beforeLogoUpload"
                :headers="tokenHeader"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 130px; height: auto;">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
            <el-form-item label="品牌简介" prop="description">
              <el-input
                v-model="ruleForm.description"
                type="textarea"
                rows="5"
              />
            </el-form-item>
            <el-form-item label="关键词" prop="keywords">
              <el-input v-model="ruleForm.keywords" size="small" />
              <p class="beizhu">
                备注：关键词列表，输入多个关键词请以英文逗号进行分割
              </p>
            </el-form-item>
            <el-form-item label="排序值" prop="sort">
              <el-input v-model="ruleForm.sort" />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="submitForm('ruleForm')"
              >提交</el-button>
              <el-button @click="$router.go(-1)">返回</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import * as api from '@/api/brand'
import { getToken } from '@/utils/auth'
// import * as categoryApi from '@/api/category'
export default {
  data() {
    return {
      UPLOAD_URL: `${process.env.VUE_APP_BASE_API}upload/brand-logo`,
      brandId: '',
      imageUrl: '',
      tokenHeader: { Authorization: getToken() },
      ruleForm: {
        name: '',
        description: '',
        keywords: '',
        logo: '',
        pinyin: '',
        sort: ''
      },
      rules: {
        name: [{ required: true, message: '请输入品牌名称', trigger: 'blur' }],
        pinyin: [
          { required: true, message: '请输入品牌首字母', trigger: 'blur' }
        ],
        logo: [{ required: true, message: '请选择品牌logo', trigger: 'blur' }],
        description: [
          { required: true, message: '请输入品牌简介', trigger: 'blur' }
        ],
        keywords: [
          {
            required: true,
            message: '请输入关键词（多个关键词以英文逗号分隔）',
            trigger: 'blur'
          }
        ]
      }
    }
  },

  mounted() {
    // 接收品牌ID参数，发送请求， 回填表单
    this.brandId = this.$route.params.id
    api.getBrand(this.brandId).then((res) => {
      console.log('根据ID查询品牌：', res)
      this.ruleForm = res.data
      const logo = this.ruleForm.logo.substring(1)
      // 显示logo图片
      this.imageUrl = `${process.env.VUE_APP_BASE_API}${logo}`
    })
  },
  methods: {
    handleLogoSuccess(res, file) {
      console.log(res)
      this.ruleForm.logo = res.data
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeLogoUpload(file) {
      const isJPGPNG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPGPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPGPNG && isLt5M
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm)
          // 修改品牌
          api.updateBrand(this.brandId, this.ruleForm).then((res) => {
            this.$message({
              showClose: true,
              message: '恭喜你，品牌修改成功',
              type: 'success'
            })
            this.$router.go(-1)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
</style>
